<template>
  <div class="history-container">
    <h1 class="history-title">浏览记录</h1>
    <div class="history-list" v-if="sortedHistory.length > 0">
      <van-card class="history-item" v-for="item in sortedHistory" :key="item.id" @click="goToProductDetail(item.id)">
        <template #title>
          <van-image :src="item.pic" width="80px" height="80px" round /> <!-- 直接使用item.pic，无需拼接域名 -->
          <div class="item-details">
            <div class="item-name">{{ item.title }}</div>
            <div class="item-price">￥{{ item.price}}</div>
            <div class="browse-time">{{ formatTime(item.browseTime) }}</div>
          </div>
        </template>
      </van-card>
    </div>
    <div class="empty-tip" v-else>
      暂无浏览记录
    </div>
    <van-button type="danger" size="small" @click="clearHistory" class="clear-button">
      清空浏览记录
    </van-button>
  </div>
</template>

<script>
import { showToast } from 'vant';

export default {
  data() {
    return {
      historyHistory: [],
    };
  },
  computed: {
    // 按浏览时间倒序排列记录
    sortedHistory() {
      return [...this.historyHistory].sort((a, b) => b.browseTime - a.browseTime);
    }
  },
  created() {
    // 读取本地存储记录
    this.historyHistory = JSON.parse(localStorage.getItem('historyHistory')) || [];
  },
  methods: {
    clearHistory() {
      this.historyHistory = [];
      localStorage.removeItem('historyHistory');
      showToast("浏览记录已清空");
    },
    goToProductDetail(id) {
      this.$router.push({ name: 'productDetail', params: { id } });
    },
    formatTime(timestamp) {
      const date = new Date(timestamp);
      return `${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`;
    }
  }
};
</script>

<style scoped>
.history-container {
  padding: 15px;
  background-color: #f8f8f8;
  min-height: 100vh;
}

.history-title {
  text-align: center;
  color: #333;
  margin-bottom: 20px;
  font-size: 24px;
}

.history-list {
  .van-card {
    margin-bottom: 15px;
    border-radius: 12px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    background-color: #fff;

    &:hover {
      box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
      transform: translateY(-1px);
      transition: all 0.3s ease;
    }
  }

  .item-details {
    margin-left: 10px;

    .item-name {
      font-size: 18px;
      font-weight: 500;
      margin-bottom: 5px;
    }

    .item-price {
      font-size: 16px;
      color: #e74c3c;
      margin-bottom: 5px;
    }

    .browse-time {
      font-size: 12px;
      color: #999;
    }
  }
}

.clear-button {
  margin-top: 20px;
  width: 100%;
}

.empty-tip {
  text-align: center;
  color: #999;
  font-size: 16px;
  margin-top: 50px;
}
</style>